package com.liuwang.meal.ui;

import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;
import java.util.List;

import com.google.gson.stream.JsonReader;
import com.liuwang.meal.R;
import com.liuwang.meal.bean.Table;
import com.liuwang.meal.bean.User;
import com.liuwang.meal.manager.OrderManager;
import com.liuwang.meal.manager.TableManager;
import com.liuwang.meal.manager.UserManager;
import com.liuwang.meal.util.HttpUtil;
import com.liuwang.meal.util.MyUtil;
import com.liuwang.meal.util.NetworkUtil;
import com.liuwang.meal.util.SharedPrefer;
import com.liuwang.meal.util.SocketUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * 登陆页面
 * 
 * @author 陈江根
 * 
 */
public class LoginActivity extends Activity {

	// 声明控件
	private Button Button_cancel, Button_login;
	private EditText EditText_password, EditText_customer_count;
	private Spinner Spinner_account, Spinner_table_no;
	private SocketUtil client;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		// 实例化组件
		findViews();
		// 初始化组件
		initViews();

		// 添加背景音乐
		startService(new Intent("com.liuwang.meal.MUSIC"));
	}

	private void findViews() {
		Button_cancel = (Button) findViewById(R.id.cancelButton);
		Button_login = (Button) findViewById(R.id.loginButton);
		Spinner_account = (Spinner) findViewById(R.id.accountSpinner);
		EditText_password = (EditText) findViewById(R.id.passwordEditText);
		Spinner_table_no = (Spinner) findViewById(R.id.table_noSpinner);
		EditText_customer_count = (EditText) findViewById(R.id.customer_countEditText);
	}

	private void initViews() {
		// 初始化服务员Spinner控件
		List<User> users = new UserManager(getApplicationContext()).queryUsers();
		String[] spinnerValue0 = new String[users.size()];
		int i0 = 0;
		for (Iterator<User> iterator = users.iterator(); iterator.hasNext(); i0++) {
			spinnerValue0[i0] = ((User) iterator.next()).getAccount();
		}
		ArrayAdapter<CharSequence> adapter0 = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item, spinnerValue0);
		Spinner_account.setAdapter(adapter0);
		// 初始化桌号Spinner控件
		List<Table> tables = new TableManager(getApplicationContext()).queryTables();
		String[] spinnerValue = new String[tables.size()];
		int i = 0;
		for (Iterator<Table> iterator = tables.iterator(); iterator.hasNext(); i++) {
			spinnerValue[i] = ((Table) iterator.next()).getNum().toString();
		}
		ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
				android.R.layout.simple_spinner_item, spinnerValue);
		Spinner_table_no.setAdapter(adapter);

		Button_cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				// 关闭背景音乐
				stopService(new Intent("com.liuwang.meal.MUSIC"));
				finish();
			}
		});

		Button_login.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				if (validate()) {
					if (login()) {
						Intent intent = new Intent(LoginActivity.this, MenuActivity.class);
						startActivity(intent);
						finish();
					} else {
						showDialog("登陆错误，请重新输入！");
					}
				}
			}
		});
	}

	// 登录方法
	private boolean login() {
		// 获得服务员工号
		String account = Spinner_account.getSelectedItem().toString();
		// 获得密码
		String password = EditText_password.getText().toString();
		// 获得桌号
		String table_no = Spinner_table_no.getSelectedItem().toString();
		Integer customer_count = Integer.parseInt(EditText_customer_count.getText().toString());
		
		try {
			SharedPrefer.SaveTableNo(getApplicationContext(), Integer.parseInt(table_no));
			
			SharedPrefer.SaveEatNum(getApplicationContext(), customer_count);
		}  catch (Exception e) {
			
			e.printStackTrace();
		}
	 
		
		// 机器码
		String machine_code = Secure.getString(getApplicationContext().getContentResolver(),
				Secure.ANDROID_ID);


		User user = new UserManager(this).query(account, password);
		Table table = new TableManager(this).query(table_no);
		if (user != null && table != null) {
			new OrderManager(this)
					.addOrder(user.get_id(), table.get_id(), table_no, customer_count);
			saveUserMsg(account);
			return true;
		} else {
			return false;
		}

		 
	}

	public void parseJson(String jsonData) {
		// 如果需要从解析json数据，首先要生成一个jsonReader对象
		JsonReader reader = new JsonReader(new StringReader(jsonData));
		try {
			// 现在开始解析
			reader.beginArray();// 开始解析数组
			while (reader.hasNext()) {
				reader.beginObject();// 开始解析对象
				while (reader.hasNext()) {
					String tagName = reader.nextName();
					if (tagName.equals("name")) {
						System.out.println(reader.nextString());
					} else if (tagName.equals("age")) {
						System.out.println(reader.nextInt());
					}
				}
				reader.endObject();// 结束对象解析
			}
			reader.endArray();// 结束数组解析
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	// 验证方法
	private boolean validate() {
		String Error_MSG = "";

		String waiter = Spinner_account.getSelectedItem().toString();
		if (waiter.equals("")) {
			Error_MSG = "服务员工号是必填项！\n";
		}
		String password = EditText_password.getText().toString();
		if (password.equals("")) {
			Error_MSG = Error_MSG + "服务员密码是必填项！\n";
		}
		String table_no = Spinner_table_no.getSelectedItem().toString();
		if (table_no.equals("") || table_no == null) {
			Error_MSG = Error_MSG + "桌号是必填项！\n";
		}
		String customer_count = EditText_customer_count.getText().toString();
		if (customer_count.equals("")) {
			Error_MSG = Error_MSG + "就餐人数是必填项！\n";
		}

		if (Error_MSG.length() > 0) {
			showDialog(Error_MSG);
			return false;
		}
		return true;
	}

	private void showDialog(String msg) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(msg).setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
					}
				});
		AlertDialog alert = builder.create();
		alert.show();
	}

	// 根据用户名称密码查询
	private String query(String account, String password, String table_no, String customer_count) {
		// 查询参数
		String queryString = "account=" + account + "&password=" + password + "&table_no="
				+ table_no + "&customer_count=" + customer_count;
		// url
		String url = HttpUtil.BASE_URL + "servlet/LoginServlet?" + queryString;
		// 查询返回结果
		return HttpUtil.queryStringForPost(url);
	}

	// 将用户信息保存到配置文件
	private void saveUserMsg(String account) {
		// 共享信息
		SharedPreferences sp = getSharedPreferences("user_msg", MODE_WORLD_WRITEABLE);
		SharedPreferences.Editor editor = sp.edit();
		editor.putString("account", account);
		editor.commit();
	}

	// 捕捉按键事件
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// 关闭背景音乐
			stopService(new Intent("com.liuwang.meal.MUSIC"));
		}
		return super.onKeyDown(keyCode, event);
	}
}